package com.krtech.wecard.module.ramble.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.model.CommRes;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.ramble.entity.RambleShareLog;
import com.krtech.wecard.module.ramble.entity.RambleShareQrcode;
import com.krtech.wecard.module.ramble.mapper.RambleDrawChanceMapper;
import com.krtech.wecard.module.ramble.service.RambleDrawChanceService;
import com.krtech.wecard.module.ramble.service.RambleShareLogService;
import com.krtech.wecard.module.ramble.service.RambleShareQrcodeService;
import com.krtech.wecard.module.sys.entity.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rambleShare")
@Slf4j
@Api(tags = "佳得乐漫步-分享管理")
public class RambleShareLogController {
    @Autowired
    private RambleShareQrcodeService shareQrcodeService;

    @Autowired
    private RambleShareLogService shareLogService;

    @Autowired
    private RambleDrawChanceMapper drawChanceMapper;

    @GetMapping("/getQrCode")
    @ApiOperation(value = "获得当前用户的二维码")
    public CommRes getQrCode() {
        String qrCode = shareQrcodeService.getQrCode();
        return CommRes.ok(qrCode);
    }

    @GetMapping("/sureShare")
    @ApiOperation(value = "确定分享")
    public boolean sureShare(String code) {
        if (StrUtil.isEmpty(code)){
            throw new BusinessException("必填参数code不能为空");
        }
        SysUser sharedUser = LoginUtil.getUserInfo();

        RambleShareQrcode sharerQrCode = shareQrcodeService.getOne(new QueryWrapper<RambleShareQrcode>().eq(RambleShareQrcode.COL_CODE, code));

        //判断当前用户是否为这个人增加过分享了
        RambleShareLog hasShare = shareLogService.getOne(new QueryWrapper<RambleShareLog>()
                .eq(RambleShareLog.COL_SHARER_PHONE, sharerQrCode.getPhone()).eq(RambleShareLog.COL_SHARED_PHONE, sharedUser.getPhone()));

        if (hasShare != null){
            return false;
        }

        RambleShareLog rambleShareLog = new RambleShareLog();
        rambleShareLog.setSharerPhone(sharerQrCode.getPhone());
        rambleShareLog.setSharerOpenId(sharerQrCode.getOpenId());

        rambleShareLog.setSharedPhone(sharedUser.getPhone());
        rambleShareLog.setSharedOpenId(sharedUser.getMipOpenId());

        shareLogService.save(rambleShareLog);

        //增加一次机会
        drawChanceMapper.incrChance(sharerQrCode.getPhone());

        return true;
    }
}
